package com.thememaker.util.packager;

import com.thememake.Constants;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.util.FileUtils;
import com.thememake.util.ZipUtil;
import com.thememaker.util.ImportScreenUtils;
import com.thememake.util.xml.ThemeDescriptionXmlUtils;
import com.thememake.util.xml.bean.DescriptionItem;
import com.thememake.util.xml.fontcolor.ReadXmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.BiConsumer;

/**
 * Created by jiajun.jiang on 2018/1/9.
 */
public class LockScreenPackager {

    private ThemeFileInfo themeFileInfo;
    private Path lockScreenPath;
    private String author = "彩虹糖";
    private String themeId = String.valueOf(System.currentTimeMillis());
    private String themeType;
    private Path outPath;

    public LockScreenPackager(ThemeFileInfo themeFileInfo, Path lockScreenPath) {
        this.themeFileInfo = themeFileInfo;
        this.lockScreenPath = lockScreenPath;
        this.themeType = themeFileInfo.getThemeType();
    }


    public LockScreenPackager(String themeType, Path lockScreenPath,Path outPath) {
        this.lockScreenPath = lockScreenPath;
        this.themeType = themeType;
        this.outPath = outPath;
    }

    public void pack(BiConsumer<String, Path> beforePack, BiConsumer<String, Path> endPack) throws Exception {
        if (themeType.equals(Constants.VIVO)){
            String[] themeTypes = {"2.5","3.0"};
            if (themeFileInfo != null){
                List<DescriptionItem> descriptionItems = ThemeDescriptionXmlUtils.clickDescriptionType(themeFileInfo.getThemeType(),themeFileInfo.getThemeDir());
                if (descriptionItems != null && descriptionItems.size() > 0){
                    for (DescriptionItem item : descriptionItems){
                        System.err.println(item.getName() + " >>> " + item.getValue());
                        if (item.getName().equals("制作部门")){
                            author = item.getValue();
                        }
                        if ("主题编号".equals(item.getName())){
                            themeId = item.getValue();
                        }
                    }
                }
            }
            themeId = String.valueOf(System.currentTimeMillis());
            for (String type : themeTypes){
                if (beforePack != null) {
                    beforePack.accept(type, lockScreenPath);
                }
                packLockScreen(type,FileUtils.getResFileOfThemeModel(themeType,"lockscreen").toPath());
                if (endPack != null) {
                    endPack.accept(type, lockScreenPath);
                }
            }
        }else {
            if (beforePack != null) {
                beforePack.accept(themeType, lockScreenPath);
            }
            packLockScreen(themeType,FileUtils.getResFileOfThemeModel(themeType,"lockscreen").toPath());
            if (endPack != null) {
                endPack.accept(themeType, lockScreenPath);
            }
        }

    }

    private void packLockScreen(String type,Path modelPath){
        try {
            Path pack = Paths.get(lockScreenPath.getParent().toString(),ThemeFileInfo.PACK_NAME);
            if (Files.exists(pack)){
                FileUtils.deleteDir(pack.toFile());
            }
            Files.createDirectories(pack);
            if (themeType.equals(Constants.VIVO)){
                FileUtils.copy(Paths.get(modelPath.toString(),type).toString(),pack.toString(),null,true,true);
                editLockInfo();
                editManifest();
                if (type.equals("2.5")) {
                    editDescription("lockscreen.xml",pack);
                    ZipUtil.zip(lockScreenPath.toFile(), Paths.get(pack.toString(),themeId+".zip").toFile());
                }else {
                    Path path =  Paths.get(pack.toString(),"lockscreen");
                    Files.createDirectories(path);
                    editDescription("description.xml",pack);
                    ZipUtil.zip(lockScreenPath.toFile(), Paths.get(path.toString(),themeId+".zip").toFile());
                }
                Path path = Paths.get(lockScreenPath.getParent().toString(),"lockscreen.itz");
                if (type.equals("2.5")){
                    path = Paths.get(lockScreenPath.getParent().toString(),"lockscreen.iuz");
                }
                ZipUtil.zip(pack.toFile(), path.toFile());
                if (themeFileInfo!=null){
                    ImportScreenUtils importScreenUtils = new ImportScreenUtils();
                    if (importScreenUtils.checkFileChooser(lockScreenPath.getParent().toFile())){
                        importScreenUtils.doImportScreen(themeFileInfo);
                    }
                }
            }else if (themeType.equals(Constants.OPPO)){
                Path path = Paths.get(lockScreenPath.getParent().toString(),"lockstyle");
                if (Files.exists(path)){
                    Files.delete(path);
                }
                FileUtils.copyDir(lockScreenPath.toString(),Paths.get(pack.toString(),"advance").toString(),true);
                ZipUtil.zip(pack.toFile(), path.toFile());
                if (themeFileInfo != null){
                    FileUtils.copyFile(path,Paths.get(themeFileInfo.getOutputDir().toString(),"lockscreen","lockstyle"),true);
                }else{
                    FileUtils.copyFile(path,Paths.get(outPath.toString(),"lockstyle"),true);
                }
                if (Files.exists(path)){
                    Files.delete(path);
                }
            }else if (themeType.equals(Constants.OS360) || themeType.equals("os360")){
                Path path = Paths.get(lockScreenPath.getParent().toString(),"lockscreen.zip");
                if (Files.exists(path)){
                    Files.delete(path);
                }
                ZipUtil.zip(lockScreenPath.toFile(), path.toFile());
                if (themeFileInfo != null) {
                    FileUtils.copyFile(path, Paths.get(themeFileInfo.getOutputDir().toString(), "lockscreen"), true);
                }else{
                    FileUtils.copyFile(path,Paths.get(outPath.toString(),"lockscreen"),true);
                }
                if (Files.exists(path)){
                    Files.delete(path);
                }
            }
            FileUtils.deleteDir(pack.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void editDescription(String name,Path pack){
        Document document = ReadXmlUtils.loadXml(Paths.get(pack.toString(),name).toString());
        Element rootElement = document.getDocumentElement();
        NodeList nodeList =  rootElement.getElementsByTagName("author");
        if (nodeList != null && nodeList.getLength() > 0){
            for (int i=0;i<nodeList.getLength();i++){
                Element element = (Element) nodeList.item(i);
                System.err.println(name + " >>> " +document.createCDATASection(author).getNodeValue());
                System.err.println(name + " >>> " +document.createCDATASection(author).getData());
                if (name.equals("lockscreen.xml")) {
                    element.setTextContent(author);
                }else {
                    element.setTextContent("");
                    element.appendChild(document.createCDATASection(author));
                }
            }
        }
        nodeList =  rootElement.getElementsByTagName("id");
        if (nodeList != null && nodeList.getLength() > 0){
            for (int i=0;i<nodeList.getLength();i++){
                Element element = (Element) nodeList.item(i);
                element.setTextContent(themeId);
            }
        }
        if (name.equals("lockscreen.xml")) {
            nodeList = rootElement.getElementsByTagName("name");
            if (nodeList != null && nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Element element = (Element) nodeList.item(i);

                    element.setTextContent(themeId);
                }
            }
        }else{
            nodeList = rootElement.getElementsByTagName("title");
            if (nodeList != null && nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Element element = (Element) nodeList.item(i);
                    element.setTextContent("");
                    element.appendChild(document.createCDATASection(themeId));
                }
            }
        }
        try {
            new ReadXmlUtils().saveXml(document,Paths.get(pack.toString(),name).toFile());
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    private void editLockInfo(){
        Path lockInfoPath = Paths.get(lockScreenPath.toString(),"lockInfo.xml");
        Path path = FileUtils.getResFileOfThemeModel(themeFileInfo.getThemeType(),"lockscreen").toPath();
        path = Paths.get(path.toString(),"lockInfo.xml");
        try {
            FileUtils.copyFile(path,lockInfoPath,true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Document document = ReadXmlUtils.loadXml(lockInfoPath.toString());
        Element rootElement = document.getDocumentElement();
        NodeList nodeList =  rootElement.getElementsByTagName("LockName");
        if (nodeList != null && nodeList.getLength() > 0){
            for (int i=0;i<nodeList.getLength();i++){
                Element element = (Element) nodeList.item(i);
                element.setTextContent(themeId);
            }
        }
        try {
            new ReadXmlUtils().saveXml(document,lockInfoPath.toFile());
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    private void editManifest(){
        Document document = ReadXmlUtils.loadXml(Paths.get(lockScreenPath.toString(),"manifest.xml").toString());
        Element rootElement = document.getDocumentElement();
        rootElement.setAttribute("id",themeId);
        try {
            new ReadXmlUtils().saveXml(document,Paths.get(lockScreenPath.toString(),"manifest.xml").toFile());
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
